#include "main.h"
/*
 *  This is a pcap example for capturing Diablo2 packets.
 */
int main(int argc, char *argv[]) {
	// Get the settings from the file.
	CSettings Settings("settings.ini");
	std::string MyFilter=Settings.GetSValue("Pcap Settings","filter","tcp port 80");
	int MyDevice=Settings.GetNValue("Pcap Settings","device",0);
	// Create a Pcap Handler class.
	TcpIp_Pcap CaptureDiablo2;
	// Initialize it, return -1 if it fails.
	if (CaptureDiablo2.Init(MyDevice,MyFilter)==0) {
		std::cerr << "Error initializing Pcap." << std::endl;
		return -1;
	}
	// Now begin capturing the packets.
	CaptureDiablo2.StartCaptureLoop(); /* This calls ParsePacket() in a loop. */
	return 0;
}

int TcpIp_Pcap::ParsePacket() {
	// Ethernet length is always 14.
	const int ethernet_length=14;
	u_char *ethernet_header=const_cast<u_char*>(Packet.data);
	u_char *ip_header=ethernet_header+ethernet_length;

	// Get the length of the ip header.
	u_char Byte=*ip_header;
	u_char TempByte=BitOp::SpliceByte(Byte,0,4);
	int ip_length=static_cast<int>(TempByte)*4; // * 32 / 8

	// Get the length of the tcp header.
	Byte=*ip_header+12;
	TempByte=BitOp::SpliceByte(Byte,4,4);
	int tcp_length=static_cast<int>(TempByte)*4; // * 32 / 8
	u_char *payload=ip_header+ip_length+tcp_length;
	int data_length=Packet.header->len-ethernet_length-ip_length-tcp_length;

	// Print the rest of the packet.
	if (data_length>0) {
		std::cout << "IP header length=" << ip_length;
		std::cout << "\tTCP header length=" << tcp_length;
		std::cout << "\tData length=" << data_length << std::endl;
		Print(payload, data_length);
	}
	// Success.
	return 1;
}

